﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.App;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core.Metadata.FormElement;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.ServiceHelper;

namespace RK.SerivesPlugin.Ronma
{
    [Description("附件明细服务插件")]
    [HotUpdate]
    public class ServicePlugnBOS_Attachment: AbstractOperationServicePlugIn
    {
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            if (this.FormOperation.OperationId == FormOperation.Operation_Save)
            {
                //获取销售出库单的附件
                var findSaleOuts = e.DataEntitys.Where(w => Convert.ToString(w["BillType"]).EqualsIgnoreCase("SAL_OUTSTOCK"));
                if (findSaleOuts != null && findSaleOuts.Count() > 0)
                {
                    //获取单据内码
                    var interIDs = findSaleOuts.Select(s => Convert.ToString(s["InterID"]));
                    //查找下推应收单的单据
                    string sql = string.Format(@"/*dialect*/
                    SELECT DISTINCT FSBILLID ,b.FID,c.FBILLNO
                    FROM t_AR_receivableEntry_LK a
                    LEFT JOIN t_AR_receivableEntry b ON b.FENTRYID = a.FENTRYID
					LEFT JOIN t_AR_receivable c ON c.FID = b.FID
                    WHERE FSTABLENAME = 'T_SAL_OUTSTOCKENTRY' AND FSBILLID IN ({0})
                    ", string.Join(",", interIDs));
                    DynamicObjectCollection rows = DBUtils.ExecuteDynamicObject(this.Context, sql);
                    if (rows.Count > 0)
                    {
                        List<DynamicObject> saveObjs = new List<DynamicObject>();
                        var outIdAndARIds = rows.GroupBy(g => Convert.ToInt64(g["FSBILLID"]))
                            .ToDictionary(t => t.Key, t => t.ToList());
                        var outIdAndObjs = findSaleOuts.GroupBy(g => Convert.ToInt64(g["InterID"]))
                            .ToDictionary(t => t.Key, t => t.ToList());
                        foreach (long outId in outIdAndARIds.Keys)
                        {
                            List<DynamicObject> orders = outIdAndObjs[outId];
                            List<DynamicObject> aRIds = outIdAndARIds[outId];
                            foreach (var order in orders)
                            {
                                bool fromDatabase = order.DataEntityState.FromDatabase;
                                if (!fromDatabase)
                                {
                                    object id = order["id"];
                                    foreach (var aRId in aRIds)
                                    {
                                        DynamicObject targDynObj = new DynamicObject(order.DynamicObjectType);
                                        foreach (DynamicProperty dynProp in order.DynamicObjectType.Properties)
                                        {
                                            if (dynProp.IsReadOnly) continue;
                                            targDynObj[dynProp.Name] = order[dynProp.Name];
                                        }
                                        targDynObj["Id"] = 0; //清空附件内码。
                                        targDynObj["INTERID"] = aRId["FID"]; //关联目标单。
                                        targDynObj["BillType"] = "AR_receivable";//应收单
                                        targDynObj["BillNo"] = aRId["FBILLNO"];
                                        targDynObj["SourceId"] = id;
                                        saveObjs.Add(targDynObj);
                                    }

                                }
                            }
                        }
                        if (saveObjs.Count() > 0)
                        {
                            ISaveService saveService = ServiceHelper.GetService<ISaveService>();
                            DynamicObject[] res = saveService.Save(this.Context, saveObjs.ToArray());
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
